package com.kylin.syn;

//不安全的买票。会拿到同一张票，或者拿到负数
public class UnsafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket ticket = new BuyTicket();

        new Thread(ticket, "苦逼的我").start();
        new Thread(ticket, "努力的你").start();
        new Thread(ticket, "可恶的黄牛").start();
    }
}

class BuyTicket implements Runnable {

    //票
    private int tickeNums = 10;
    boolean flag = true;//外部停止方式

    @Override
    public void run() {
        //买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //加上synchronized 同步方法 锁的是this对象 也就是BuyTicket类
    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (tickeNums <= 0) {
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);
        //买到票
        System.out.println(Thread.currentThread().getName() + "拿到" + tickeNums-- + "票");
    }
}
